# -*- coding: utf-8 -*-

import json

from django.views.decorators.http import require_POST, require_GET

from common.bankcard import db as bankcard_db
from common.console import db as user_db
from common.mch import db as mch_db
from common.transaction import db as trans_db
from common.transaction.model import TRANS_TYPE, TRANS_TARGET_TYPE
from common.utils import track_logging
from common.utils.api import token_required, check_params
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)


@require_POST
@token_required
@response_wrapper
def create_manual_trans(req):
    params = json.loads(req.body)
    check_params(params, ['card_name', 'amount', 'target_card_name',
                          'desc', 'addition_amount', 'target_type']
                 )
    card_info = bankcard_db.get_bankcard_by_name(params['card_name'])
    if float(params['amount']) <= 0:
        raise ParamError('amount not valid')
    params['card_id'] = card_info.id
    if params['target_type'] == TRANS_TARGET_TYPE.INTERNAL_OUT:
        target_card_info = bankcard_db.get_bankcard_by_name(params['target_card_name'])
        if not target_card_info:
            raise ParamError('target card not exist')
        params['target_card_id'] = target_card_info.id
    params['mch_id'] = card_info.mch_id
    _LOGGER.info('create manual trans request: %s' % params)
    params['admin'] = req.user.username
    trans = trans_db.create_manual_trans(params)
    return {}


@require_GET
@token_required
@response_wrapper
def get_manual_trans_detail(req, trans_id):
    item = trans_db.get_manual_trans(trans_id)
    data = item.as_dict()
    data['created_at'] = utc_to_local_str(data['created_at'])
    data['updated_at'] = utc_to_local_str(data['updated_at'])
    return data


@require_POST
@token_required
@response_wrapper
def update_manual_trans(req, trans_id):
    params = json.loads(req.body)
    check_params(params, ['desc'])
    trans = trans_db.update_manual_trans(trans_id, params['desc'])
    return {}


@require_GET
@token_required
@response_wrapper
def list_manual_trans(req):
    query_dct = req.GET.dict()
    query_dct['trans_type'] = str(TRANS_TYPE.MANUAL)
    cond = user_db.get_mchids_filter_by_user(req.user_id)
    if cond and query_dct.get('mch_id') is None:
        query_dct['mch_id'] = cond
    items, total_count, total_amount = trans_db.list_trans(query_dct)
    mch_dct = mch_db.get_mch_dct()

    resp_items = []
    for item in items:
        data = item.as_dict()
        data['mch_id'] = mch_dct.get(data['mch_id'], '-')
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        resp_items.append(data)
    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'size': len(resp_items), 'total_count': total_count}
